<?php

use app\modules\Admin\models\qudaiapplyModel;
use Illuminate\Database\Capsule\Manager as DB;

#[区域代理申请管理]
class QudaiapplyController extends AcommonController {

    public function init() {
        $this->model = new qudaiapplyModel();
        $this->table = 'qudai_apply';
        $this->primaryKey = 'id';
        parent::init();
    }
    
    #[区域代理申请列表]
    public function indexAction($returnData = FALSE)
    {
        if ($this->isPost()){
            $this->model = $this->model->with(['member', 'qudai_level']);
            $level = $this->get('level', 'all');
            if(!in_array($level, ['xianqu', 'shiji'])){
                $level = 'all';
            }
            if ($level !== 'all'){
                if ($level === 'shiji'){
                    $this->model = $this->model->where('area_level', 2);
                }else{
                    $this->model = $this->model->where('area_level', 3);
                }
            }
            $mode = $this->get('mode', 'all');
            $post_data = $this->postData;
            switch ($mode){
                case 'reject':
                    array_push($this->search,['status', '=', -1]);
                    break;
                case 'waiting':
                    array_push($this->search,['status', '=', 0]);
                    break;
                case 'accepted':
                    array_push($this->search,['status', '=', 1]);
                    break;
            }
            if(isset($post_data['qudaiapply_start']) && !empty($post_data['qudaiapply_start'])){
                $this->model = $this->model->whereDate('created_at', '>=', $post_data['qudaiapply_start']);
            }
            if(isset($post_data['qudaiapply_end']) && !empty($post_data['qudaiapply_end'])){
                $this->model = $this->model->whereDate('created_at', '<=', $post_data['qudaiapply_end']);
            }
            $keywordsTypeArray = [
                'user_id' => 'user_id',
                'user_phone' => 'user_phone',
            ];
            if(isset($post_data['keywordsType']) && isset($post_data['keywords'])
                && in_array($post_data['keywordsType'], $keywordsTypeArray)
                && !empty($post_data['keywords'])){
                if($post_data['keywordsType'] == $keywordsTypeArray['user_id'] && is_numeric($post_data['keywords']) && intval($post_data['keywords']) > 0){
                    array_push($this->search, ['member_id', '=', $post_data['keywords']]);
                }
                if($post_data['keywordsType'] == $keywordsTypeArray['user_phone']){
                    if(mb_strlen($post_data['keywords'], 'utf-8') < 4){
                        array_push($this->search, ['id', '=', 0]);
                    }else{
                        array_push($this->condition_in, ['member_id', memberModel::query()->where('phone', 'like', "%{$post_data['keywords']}%")->pluck('id')->toArray()]);
                    }
                }
            }
            unset($keywordsTypeArray);
        }else{
            $this->_view->assign('all_status', json_encode(['all'=>'全部',
                'reject' => '驳回',
                'waiting'  => '未审核',
                'accepted'  => '已通过'
            ], JSON_UNESCAPED_UNICODE));
        }
        return parent::indexAction($returnData); // TODO: Change the autogenerated stub
    }

    #[区域代理申请详情]
    public function viewAction($returnData = FALSE)
    {
        $id = $this->get('id', 0);
        try {
            $apply = qudaiapplyModel::with(['member', 'qudai', 'qudai_level'])->findOrFail($id);
            $apply->reason_user_name = '';
            if($apply->reason_user){
                $apply->reason_user_name = adminModel::query()->where('id', $apply->reason_user)->value('username');
            }
            $this->_view->assign('dataset', json_encode($apply, JSON_UNESCAPED_UNICODE));
            $this->_view->display( strtolower($this->controller) . '/view.html');
        }catch (Exception $e){
            ret(3001, $e->getMessage());
        } finally {
            unset($id);
        }
    }

    #[申请图片查看]
    public function showpicAction()
    {
        $id = $this->get('id', 0);
        try {
            $apply = qudaiapplyModel::findOrFail($id);
            $mode = $this->get('mode', 0);
            switch ($mode){
                case 0:
                    $image = $apply->company_license_image;
                    break;
                case 1:
                    $image = $apply->company_representative_idcard_front_image;
                    break;
                case 2:
                    $image = $apply->company_representative_idcard_reverse_image;
                    break;
                case 3:
                    $image = $apply->company_representative_idcard_hand_image;
                    break;
                default:
                    $image = '';
            }
            if(!empty($image)){
                $this->_view->assign('img', $image);
                $this->_view->display( strtolower($this->controller) . '/showpic.html');
            }else{
                throw new Exception('图片地址不存在');
            }
        }catch (Exception $e){
            throw new Exception('申请不存在');
        }
    }

    #[设置区域代理申请代理费用]
    public function feeeditAction()
    {
        $id = $this->get('id', 0);
        try {
            $apply = $this->model->findOrFail($id);
            if ($this->isPost()){
                $params = $this->postData;
                if(!is_numeric($params['agent_fee']) || $params['agent_fee'] <= 0){
                    ret(11, '代理费用非法或小于0');
                }
                $res   = DB::transaction(function () use ($apply, $params) {
                    $apply->agent_fee = $params['agent_fee'];
                    $apply->agent_fee_pay_status = $params['agent_fee_pay_status'];
                    $apply->agent_fee_payed_id = $params['agent_fee_payed_id'];
                    $apply->updated_at = timestamp();
                    return $apply->save();
                });
                if($res){
                    ret(0, '恭喜，代理费及支付设置成功！');
                }else{
                    ret(1, '抱歉，代理费及支付设置失败！');
                }
            }else{
                $this->_view->assign('dataset', $apply->toJson());
                $this->_view->display( strtolower($this->controller) . '/feeedit.html');
            }
        }catch (Exception $e){
            if($this->isPost()){
                ret(1, '代理申请不存在');
            }else{
                throw new Exception('代理申请不存在');
            }
        } finally {
            unset($id, $apply);
        }
    }

    #[获取用户有效订单]
    public function getorderAction()
    {
        $id = $this->get('id', 0);
        if($this->isPost()){
            $params = $this->postData;
            $query = \orderModel::query()->with(['member', 'item'])->where('member_id', $id)->where('status', '>','0')->whereNotExists(function ($query) {
                $query->from('order_item')->whereColumn('order_item.order_id', 'order.id')
                      ->where('refund_status', '>', 0);
            })->where(function ($query){
                $query->whereNull('deleted_at')->orWhereDate('deleted_at', '>', '0000-00-00');
            })->orderByDesc('created_at');
            $start_on     = $params['start_on'];
            $end_on       = $params['end_on'];
            $keywordsType = $params['keywordsType'];
            $keywords     = $params['keywords'] ?? '';
            if (!empty($start_on)) {
                $query = $query->whereDate('created_at', '>=', $start_on);
            }
            if (!empty($end_on)) {
                $query = $query->whereDate('created_at', '<=', $end_on);
            }
            if (!empty($keywords)) {
                switch ($keywordsType) {
                    case 'order_id':
                        $query = $query->where('id', $keywords);
                        break;
                    case 'order_sn':
                        $query = $query->where('order_sn', 'like', "%{$keywords}%");
                        break;
                    case 'member_id':
                        $query = $query->where('member_id', $keywords);
                        break;
                    case 'member_phone':
                        $query = $query->whereIn('member_id', DB::table('member')->where('phone', 'like', "%{$keywords}%")->limit(20)->pluck('id'));
                        break;
                    case 'customer_id':
                        $query = $query->where('customer_id', $keywords);
                        break;
                    case 'consignee':
                        $query = $query->where('consignee', $keywords);
                        break;
                    case 'consignee_phone':
                        $query = $query->where('phone', 'like', "%{$keywords}%");
                        break;
                }
            }

            $page = $this->get('page', 1);
            if (!empty($page)) {
                $limit = $this->get('rows', 10);
                $offset = ($page - 1) * $limit;
                $query = $query->offset($offset)->limit($limit);
            }
            $orderList = $query->get()->append('status_name')->toArray();
            json(['total' => count($orderList), 'rows' => $orderList]);
        }else{
            $this->_view->assign('id', $id);
            $this->_view->display( strtolower($this->controller) . '/getorder.html');
        }
    }

    #[删除区域代理申请]
    public function deleteAction()
    {
        if ($this->isPost()){
            $id = $this->get('id', 0);
            try{
                $qudaiApply = $this->model->findOrFail($id);
                if($qudaiApply->status === 1){
                    if (qudaiModel::query()->where('apply_id', $id)->exists()){
                        ret('2', '删除失败，此申请已经通过<br>如确定要删除，请先 [删除并销毁区域代理] 后再进行删除操作！');
                    }
                }
            }catch (Exception $e){
                ret(1, '区域代理申请不存在');
            } finally {
                unset($id);
            }
            parent::deleteAction(); // TODO: Change the autogenerated stub
        }else{
            ret(2000, '请求出错！');
        }
    }

    #[同意区域代理申请]
    public function applysuccessAction()
    {
        if($this->isPost()){
            $opt_id = $this->postData['id'];
            try {
                $applyModel = $this->model->findOrFail($opt_id);
                if($applyModel->status !== 0){
                    ret(5, '申请已经处理过，不能重复处理！');
                }
                if(qudaiModel::query()->where('qudai_id', $applyModel->member_id)->exists()){
                    ret(5, '已经是区域代理，不能再次成为区域代理！');
                }
                if(qudaiModel::query()->where('area_level', $applyModel->area_level)->where('area', $applyModel->area)->exists()){
                    ret(5, "{$applyModel->area_name}当前区域已经有代理，不能重复设置！");
                }
                $res = DB::transaction(function () use ($applyModel) {
                    $applyModel->status = 1;
                    $applyModel->updated_at = timestamp();
                    if($applyModel->save()){
                        $created_at = timestamp();
                        $save_status = qudaiModel::query()
                                         ->insert([
                                                       'qudai_id' => $applyModel->member_id,
                                                       'area' => $applyModel->area,
                                                       'area_name' => $applyModel->area_name,
                                                       'area_level' => $applyModel->area_level,
                                                       'apply_id' => $applyModel->id,
                                                       'company_name' => $applyModel->company_name,
                                                       'company_representative_name' => $applyModel->realname,
                                                       'phone' => $applyModel->phone,
                                                       'created_at' => $created_at,
                                                       'updated_at' => $created_at,
                                                   ]);
                        $log = [
                            'qudai_id'   => $applyModel->member_id,
                            'event'      => 'signin',
                            'remark'     => '管理员同意区域代理申请，所在区域为：' . $applyModel->area_name,
                            'oper_type'  => 'admin',
                            'oper_id'    => $this->auth->user_id,
                            'created_at' => $created_at
                        ];
                        qudailogModel::insert($log);
                        return $save_status;
                    }else{
                        return false;
                    }
                });
                if($res){
                    ret(0, '恭喜，同意区域代理申请成功！');
                }else{
                    ret(1, '抱歉，区域代理申请操作失败！');
                }
            }catch (Exception $exception){
                ret(2, '操作失败，申请记录不存在或已处理！');
            }
            unset($applyModel);
            unset($opt_id);
        }else{
            ret(500, '请求失败，非正常请求！');
        }
    }

    #[拒绝区域代理申请]
    public function applyrefuseAction()
    {
        if($this->isPost()){
            $opt_id = $this->postData['id'];
            $remark = $this->postData['remark']?:'无';
            try {
                $apply = $this->model->findOrFail($opt_id);
                if($apply->status !== 0){
                    ret(5, '申请已经处理过，不能重复处理！');
                }
                $user = memberModel::find($apply->member_id);
                if(!$user){
                    ret(4, '操作失败，申请的用户不存在！');
                }
                $res = DB::transaction(function () use ($apply, $remark, $user) {
                    $apply->status = -1;
                    $apply->reason = $remark;
                    $apply->reason_user = $this->auth->user_id;
                    $apply->reason_time = timestamp();
                    $apply->updated_at = timestamp();
                    return $apply->save();
                });
                if($res){
                    ret(0, '恭喜，拒绝区域代理申请操作成功！');
                }else{
                    ret(1, '抱歉，区域代理申请操作失败！');
                }
            }catch (Exception $e){
                ret(2, '操作失败，申请记录不存在或已处理！');
            } finally {
                unset($opt_id, $remark, $apply, $user, $res);
            }
        }else{
            ret(500, '请求失败，非正常请求！');
        }
    }

    #[修改区域代理申请]
    public function areaeditAction()
    {
        $id = $this->get('id', 0);
        try {
            $apply = $this->model->findOrFail($id);
            if ($apply->status !== 0){
                throw new Exception('申请已经审核完成，无法修改！', 30001);
            }
            if ($this->isPost()){
                $params = $this->postData;
                if(!is_numeric($params['area']) || $params['area'] <= 0){
                    ret(11, '代理区域没有填写');
                }
                $res   = DB::transaction(function () use ($apply, $params) {
                    $apply->area_name = $params['area_name'];
                    $apply->area = $params['area'];
                    $apply->area_level = $params['area_level'];
                    $apply->realname = $params['realname'];
                    $apply->company_name = $params['company_name'];
                    $apply->phone = $params['phone'];
                    $apply->updated_at = timestamp();
                    return $apply->save();
                });
                if($res){
                    ret(0, '恭喜，代理信息修改成功！');
                }else{
                    ret(1, '抱歉，代理信息修改失败！');
                }
            }else{
                $applyInfo = [
                    'id' => $apply->id,
                    'member_id' => $apply->member_id,
                    'area_level' => $apply->area_level,
                    'realname' => $apply->realname,
                    'company_name' => $apply->company_name,
                    'phone' => $apply->phone,
                ];
                $city_id = $apply->area;
                $applyInfo['area_id'] = 0;
                if($apply->area_level === 3){
                    $area = DB::table('area')->find($apply->area);
                    $applyInfo['area_id'] = $apply->area;
                    $applyInfo['area_name'] = $area->name;
                    $city_id = $area->pid;
                    unset($area);
                }
                $applyInfo['city_id'] = $city_id;
                $cityModel = DB::table('area')->find($city_id);
                $applyInfo['city_name'] = $cityModel->name;
                $applyInfo['province_id'] = $cityModel->pid;
                $applyInfo['province_name'] = DB::table('area')->where('id', $cityModel->pid)->value('name');
                unset($cityModel, $city_id, $apply);
                $prov = DB::table('area')->where('level', 1)->get();
                $city = DB::table('area')->where('level', 2)->get();
                $area = DB::table('area')->where('level', 3)->get();
                $qudai_level = qudailevelModel::query()->pluck('name', 'level');
                $this->_view->assign('prov', $prov->toJson());
                $this->_view->assign('city', $city->toJson());
                $this->_view->assign('area', $area->toJson());
                $this->_view->assign('qudai_level', json_encode($qudai_level, 256));
                $this->_view->assign('dataset', json_encode($applyInfo, 256));
                $this->_view->display( strtolower($this->controller) . '/areaedit.html');
            }
        }catch (Exception $e){
            if($this->isPost()){
                ret(1, ($e->getCode() === 30001)?$e->getMessage():'代理申请不存在');
            }else{
                throw new Exception(($e->getCode() === 30001)?$e->getMessage():'代理申请不存在');
            }
        } finally {
            unset($id, $apply);
        }
    }
}
